import Taro from '@tarojs/taro';
/**
 * 支付方法
 * @param pay_config 支付参数
 * @param type 1：商品，2：服务
 * @param orderCode 订单编号
 */
export function payOrderUtils({ orderCode, pay_config, type, price }) {
  const { nonceStr, package: packageStr, paySign, signType, timeStamp } = pay_config;
  let path = type === 1 ? '/subPages/order/result/index' : '/subPages/service/result/index';
  Taro.requestPayment({
    timeStamp,
    nonceStr,
    package: packageStr,
    signType,
    paySign,
    success: (res) => {
      console.log('res: ', res);
      if (res) {
        Taro.redirectTo({
          url: `${path}?res=1&orderCode=${orderCode}&price=${price}`,
        });
      }
    },
    fail: (err) => {
      console.log('err: ', err);
      if (err?.errMsg.indexOf('cancel')) {
        // 用户主动取消支付
        Taro.redirectTo({
          url: `${path}?res=0&orderCode=${orderCode}&price=${price}`,
        });
      } else {
        Taro.redirectTo({
          url: `${path}?res=2&orderCode=${orderCode}$price=${price}`,
        });
      }
    },
  });
}

/**
 * 后端订单状态映射前端订单状态
 * @param order_status 后端订单状态
 */
export const getOrderStatus = (order_status: number) => {
  /**
   * 101: '待付款',    === 101 支付失败
    1011: '待自提',
    102: '已取消',
    103:'订单超时取消'
    201: '待发货',   === 201 支付成功
    202: '申请退款',
    203: '已退款',
    301: '已发货',
    401: '已完成'
    1002 待服务-线下支付
    1003
   */

  /**
   * 1：待支付
   * 2：待自提，待配送，待收货，待服务
   * 3：已完成
   * 4：已取消
   * 5: 申请退款
     6： '已退款',
   */

  if (order_status === 101) {
    return 1;
  }
  if (
    order_status === 1011 ||
    order_status === 201 ||
    order_status === 301 ||
    order_status === 1002 ||
    order_status === 1003
  ) {
    return 2;
  }
  if (order_status === 401) {
    return 3;
  }
  if (order_status === 102 || order_status === 103) {
    return 4;
  }
  if (order_status === 202) {
    return 5;
  }
  if (order_status === 203) {
    return 6;
  }
};
